package com.fayou.mq.rabbitmqconsumer.consumer;

import com.fayou.cloud.entites.User;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.Consumer;

@Component
//@RabbitListener(queues = "ityu.order.cancel")
//配置监听的哪一个队列，同时在没有queue和exchange的情况下会去创建并建立绑定关系

@Slf4j
public class Customer1 {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ityu.order.cancel",durable = "true"),
            exchange = @Exchange(name="ityu.order.topic",durable = "true",type = "topic"),
            key = "*.order.*"
    )
    )
    @RabbitHandler
    public void handleUser(Channel channel, @Payload User user, @Headers Map<String,Object> headers){
        log.info(",user:"+user/*+""+message.getMessageProperties().toString()*/);
        headers.keySet().forEach(new Consumer<String>() {
            @Override
            public void accept(String key) {
              //  log.info("key:"+key+",vaule:"+headers.get(key));
//                System.out.println("key:"+key+",vaule:"+headers.get(key));
            }
        });

        //        //手动ack
//        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

//    @RabbitListener(queues = "ityu.order.cancel", containerFactory="rabbitListenerContainerFactory")
//    @RabbitHandler
//    public void handle(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, @Header Map<String,Object> heads, Message message, @Payload String body) throws IOException {
//        System.out.println(System.currentTimeMillis());
//        System.out.println(msg);
//        System.out.println(body);
//
//        System.out.println(heads);
//        //手动ack
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
////        try {
////            /**
////             * 防止重复消费，可以根据传过来的唯一ID先判断缓存数据库中是否有数据
////             * 1、有数据则不消费，直接应答处理
////             * 2、缓存没有数据，则进行消费处理数据，处理完后手动应答
////             * 3、如果消息 处理异常则，可以存入数据库中，手动处理（可以增加短信和邮件提醒功能）
////             */
////        } catch (IOException e) {
////            e.printStackTrace();
////            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
////        }
//
//
//    }

}
